# -*- coding: utf-8 -*-
# @Time    : 2024/1/11  14:42
# @Author  : zhanghao
# @FileName: worker.py
# @Software: PyCharm
"""
    Description: 任务分配者
"""
from PyQt6.QtCore import QThread, pyqtSignal

from multiprocessing import Pipe

from domain.table_info import TableInfo
from domain.signal_unit import SignalUnit
from config.logger import Logger
from helper.status import Status
from helper.event_type import EventType

import os
import shutil


class Master(QThread):
    # 中间结果文件夹
    base_dir_name = 'ocrCacheDir'
    cache_dir_path = ''

    logger = Logger().get()

    table_data: list[TableInfo]

    # 信号-用于主线程更新主界面
    signal = pyqtSignal(SignalUnit)
    conn_main: Pipe

    def __init__(self, conn_main):
        super().__init__()
        self.conn_main = conn_main
        current_path = os.getcwd()
        self.cache_dir_path = current_path + '/' + self.base_dir_name

    def initData(self, table_data):
        self.table_data = table_data

    def run(self) -> None:
        self.logger.info(str(os.getpid()) + 'master 开始分配任务......')
        self.process(self.table_data)

    # 核心处理
    def process(self, table_data: list[TableInfo]):
        self.clearAllTempDir()
        if table_data and len(table_data) > 0:
            task_id = 3
            for data in table_data:
                # 发送要处理的数据
                self.logger.info('master 分配任务......' + str(data.idx))
                self.conn_main.send(data)

                if data.idx == task_id:
                    break

            failed_task = 0
            for idx in range(len(table_data) * 2):
                self.logger.info('master 开始接收任务结果', idx)
                recv_data = self.conn_main.recv()
                recv_data.task_total = len(table_data)
                if recv_data.task_status == Status.FAILED:
                    failed_task += 1
                recv_data.task_failed = failed_task
                self.logger.info('master 任务失败数', failed_task)
                self.logger.info('master 接收任务结果', recv_data)
                self.logger.info(recv_data)
                self.signal.emit(recv_data)

                if recv_data.event_type == EventType.END_PROCESS and len(table_data) > task_id:
                    self.logger.info('master 分配任务......' + str(table_data[task_id].idx))
                    self.conn_main.send(table_data[task_id])
                    task_id += 1

    def clearAllTempDir(self):
        folder_path = self.cache_dir_path
        if os.path.exists(folder_path):
            folder_list = os.listdir(folder_path)

            for path_name in folder_list:
                folder_name = os.path.join(folder_path, path_name)
                # 删除临时文件夹
                shutil.rmtree(folder_name)
